//
//  XJSureOrderViewController.m
//  XinJiangMall
//
//  Created by RaoBo on 2018/6/11.
//  Copyright © 2018年 Tzyang. All rights reserved.
//  这个是要调接口的。
// http://xinjiangapi.zertone1.com/api/v1/order/balance?quantity=1&options_id=131&goods_id=140


#import "XJSureOrderViewController.h"

// Controller
#import "XJAddressViewController.h" // 选者收货地址。
#import "XJPayViewController.h" //支付

//view
#import "XJSureOrderHeaderView.h" // 表头
#import "XJSureOrderCell.h"
#import "XJSureOrderSectionHeaderView.h"
#import "SureOrderSectionFooterView.h"
#import "XJSureOrderBottomView.h"
#import "XJSureOrderFailView.h" //6-23失败view

//Model
#import "XJSureOrderShopModel.h"
#import "XJSureOrderGoodsModel.h"
#import "XJSureOrderAddressModel.h"
#import "XJAddressModel.h" // 用他的 addressId 判断是否选中了收货地址



@interface XJSureOrderViewController ()<UITableViewDelegate,UITableViewDataSource,XJSureOrderFailViewDelegage>

@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) XJSureOrderHeaderView *headerView;
@property(nonatomic, strong) XJSureOrderBottomView *bottomView;
@property(nonatomic, strong) XJSureOrderFailView *failView;


/**单独记录总费用*/
@property (nonatomic, copy) NSString *total_fee;
/**数组源数组*/
@property(nonatomic, strong) NSMutableArray<XJSureOrderShopModel *> *dataArray;

// 请求参数
/**1.单独记录收货地址id。根据收货地址是否有值判断是否选择了收货地址 ✅*/
@property (nonatomic, copy) NSString *receiveAddresId;

/**2.单独记录 店铺id ✅*/
@property (nonatomic, copy) NSString *shopId;


@end

@implementation XJSureOrderViewController

#pragma mark - 一 lazy
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        // 注册
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"XJSureOrderCell.h"];
        
        [_tableView registerNib:[UINib nibWithNibName:@"XJSureOrderCell" bundle:nil] forCellReuseIdentifier:@"XJSureOrderCell"];
        [_tableView registerClass:[XJSureOrderSectionHeaderView class] forHeaderFooterViewReuseIdentifier:@"XJSureOrderSectionHeaderView"];
        
        [_tableView registerClass:[SureOrderSectionFooterView class] forHeaderFooterViewReuseIdentifier:@"SureOrderSectionFooterView"];
    }
    return _tableView;
}

- (XJSureOrderHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[XJSureOrderHeaderView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 80)];
        
        XJWeakSelf(self);
        _headerView.selectAddressBlock = ^{
            
            XJAddressViewController *addressVC = [[XJAddressViewController alloc] init];
            
            addressVC.passAddresModelBlock = ^(XJAddressModel *addressModel) {
                XJLog(@"%@",addressModel);
                //第二次给收货地址属性赋值。
                weakself.receiveAddresId = addressModel.addressId;
                
                //在这里面重新赋值。
                weakself.headerView.addressModel = addressModel;
                
            };
            
            [weakself.navigationController pushViewController:addressVC animated:YES];
        };
    }
    return _headerView;
}

//h:40
- (XJSureOrderBottomView *)bottomView {
    if (!_bottomView) {
        
        _bottomView = [[XJSureOrderBottomView alloc] initWithFrame:CGRectMake(0, KHeight - kStatusBarAndNavigationBarHeight - 50, KWidth, 50)];
        
        
        XJWeakSelf(self)
        _bottomView.buyBtnBlock = ^{
            XJLog(@"立即购买");
            
            [weakself buyBusinessLogic];
            
        };
    }
    return _bottomView;
}

//1.hidden 默认 YES .  2.添加在self.tableView上
- (XJSureOrderFailView *)failView {
    if (!_failView) {
        _failView = [[XJSureOrderFailView alloc] initWithFrame:self.view.bounds];
        _failView.delegate = self;
        
        _failView.hidden = YES;

    }
    return _failView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

#pragma mark - 二生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    XJLog(@"%f",kStatusBarAndNavigationBarHeight);
    self.navTitle = @"确认订单";
    
    [self requestData];
    
    self.tableView.frame = CGRectMake(0, 0, KWidth, KHeight - kStatusBarAndNavigationBarHeight);
    [self.view addSubview:self.tableView];
    
    // 表头 表尾
    self.tableView.tableHeaderView = self.headerView;
    
    [self.view addSubview:self.bottomView];
    
    [self.view addSubview:self.failView];
}


#pragma mark - 三  UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    return 1;
    XJSureOrderShopModel *shopM = self.dataArray[section];
    return shopM.goods.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    XJSureOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XJSureOrderCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    XJSureOrderShopModel *shopModel = self.dataArray[indexPath.section];
    XJSureOrderGoodsModel *goodsModel  = shopModel.goods[indexPath.row];
    
    cell.goodsModel = goodsModel;
    
    return cell;
}

#pragma mark -  UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    XJSureOrderSectionHeaderView *sectionHeaderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"XJSureOrderSectionHeaderView"];
    
    XJSureOrderShopModel *shopM = self.dataArray[section];
    
    [sectionHeaderView configureXJSureOrderSectionHeaderViewWithShopName:shopM.name];
    
    return sectionHeaderView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    SureOrderSectionFooterView *sectionFooterView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SureOrderSectionFooterView"];

    XJSureOrderShopModel *shopM = self.dataArray[section];

    
    NSString *cnt = [NSString stringWithFormat:@"%@",shopM.total_quantity];
    
    NSString * totalFee = [NSString stringWithFormat:@"%@",shopM.total_goods_fee];
    NSString *expressFee = [NSString stringWithFormat:@"%@",shopM.express_fee];
    
    [sectionFooterView configureSureOrderSectionFooterViewCnt:cnt totalPrice:totalFee tihuoAddress:@"无" freight:expressFee isShowKuaiDi:YES];
    return sectionFooterView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 200; // h:200
}


#pragma mark - 四 立即购买业务逻辑
- (void)buyBusinessLogic{

    // 根据地址id判断是否选择了地址。
    
    if ([NSString isEmptyString:self.receiveAddresId]) {
        [JRToast showWithText:@"请选择收货地址"];
        return;
    }
    
    
    if (self.dataArray.count==0) {
        return;
    }
    
    
    
    //↓↓↓↓↓↓↓↓↓↓------------组装请求参数------------------↓↓↓↓↓↓↓↓↓↓
    //有雷:特别小心向Dic、Arr插入 nil 对象。
    NSMutableArray *dArray = [NSMutableArray array]; // data数组为防止和self.dataArray重名。命名为dArray.
    
    for (XJSureOrderShopModel *shopM in self.dataArray) {
        NSMutableDictionary *shopDic = [NSMutableDictionary dictionary];
        
        //防止奔溃处理。
        NSString *shopId = [NSString stringWithFormat:@"%@",shopM.shopId];
        if ([NSString isEmptyString:shopId]) {
            [shopDic setObject:@"" forKey:@"shop_id"];
        }else {
            [shopDic setObject:shopM.shopId forKey:@"shop_id"];
        }
        
        [shopDic setObject:@"请尽快发货" forKey:@"remark"];
        
        
        NSMutableArray *tempGoodsArr = [NSMutableArray array];
        
        for (XJSureOrderGoodsModel *goodsM in shopM.goods) {
            NSMutableDictionary *goodsDic = [NSMutableDictionary dictionary];
            NSString *quantity = [NSString stringWithFormat:@"%@",goodsM.quantity];
            NSString *goods_id = [NSString stringWithFormat:@"%@",goodsM.goodsId];
            if (![NSString isEmptyString:quantity]) { // 非空才进行赋值
                [goodsDic setObject:quantity forKey:@"quantity"];
            }
            if (![NSString isEmptyString:goods_id]) {
                [goodsDic setObject:goods_id forKey:@"goods_id"];

            }
            
            [tempGoodsArr addObject:goodsDic];
        }
        
        
        if (tempGoodsArr.count) { // 如果有值
            [shopDic setObject:tempGoodsArr forKey:@"goods"];
        }else { // 没值 直接传一个空的数组
            [shopDic setObject:@[] forKey:@"goods"];
        }
        
        [shopDic setObject:@"2" forKey:@"shipping_type"]; // 自提还是快递.目前搞不清楚数组的情况。暂时固定为2
        
        [dArray addObject:shopDic];
    }
    
//    XJLog(@"转换后的dArray是:%@",dArray);

    if (!dArray.count) {
        XJLog(@"dArray为空 操作无效");
        return;
    }
    
    //能走到这一步 肯定都不为空。
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    [parDic setObject:dArray forKey:@"data"];
    [parDic setValue:@"" forKey:@"cart_ids"];
    [parDic setObject:self.receiveAddresId forKey:@"address_id"];
    //↑↑↑↑↑↑↑↑↑↑----------组装请求参数------------------↑↑↑↑↑↑↑↑↑↑
    
    
    
    // 作用生成订单:请求成功之后服务器会返回一个订单号 向这样  SN18061309460500000008
    [XJHttpTool requestOrderGenerateOrderWithDic:parDic successH:^(id responseObjc) {
        //        XJLog(@"成功：%@",responseObjc);
        NSData *JSONData = [NSJSONSerialization dataWithJSONObject:responseObjc options:NSJSONWritingPrettyPrinted error:nil];
        
        NSString *jsonStr = [[NSString alloc] initWithData:JSONData encoding:NSUTF8StringEncoding];
        XJLog(@"%@",jsonStr);
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) { //请求成功
            
            //组装请求参数
            NSString *foreign_infos = [self assembleOrderSNWithResponseObject:responseObjc];
            
            NSString *order_amount = [NSString stringWithFormat:@"%@",responseObjc[@"data"][@"content"][@"totalFee"]];
            NSString *order_type = @"2"; //购买商品
            
            XJPayViewController *payVC = [XJPayViewController new];
            //                payVC.parDic = responseObjc;
            payVC.foreign_infos = foreign_infos;
            payVC.order_amount = order_amount;
            payVC.order_type = order_type;
            
            // "pay/prepay 的 'code'字段如果是直接购买传0,从待支付页面进入传1"
            if (self.comeFromVC == XJComeFromTypeRBGoodsDetailViewController) {
                payVC.code = @"0";
            }else {
                payVC.code = @"1";
            }
            
            [self.navigationController pushViewController:payVC animated:YES];
        }
        
    } failH:^(NSError *error) {
        XJLog(@"失败:%@",error);
    }];
    
}

//请求参数参考示例 抓包抓的
/**
 {
 "data":[
 {
 "shop_id":12,
 "remark":"",
 "goods":[
 {
 "quantity":1,
 "goods_id":110
 }
 ],
 "shipping_type":2
 }
 ],
 "cart_ids":null,
 "address_id":11
 }
 */

// 请求成功服务器返回数据示例
/**
 
 {
 "data" : {
 "content" : {
 "balance" : 0,
 "totalFee" : 10,
 "order_sns" : [
 "SN18061311550500000017"
 ]
 }
 },
 "code" : 0
 }

 */

#pragma mark - 五 网络请求
//请求数据
- (void)requestData {
    
    NSDictionary *qingQiuCanShuDic = nil;
    switch (self.comeFromVC) {
        case XJComeFromTypeRBGoodsDetailViewController:
        {
            XJLog(@"从商品详情--立即购买进来的%@",self.parDic);
            qingQiuCanShuDic = self.parDic;
            XJLog(@"请求参数:%@",qingQiuCanShuDic);

        }
            break;
        case XJComeFromTypeXJShopCartViewController:{
            XJLog(@"从购物车进来的:%@",self.cartDic);
            qingQiuCanShuDic = self.cartDic;
            XJLog(@"请求参数:%@",qingQiuCanShuDic);
        }
        default:
            break;
    }
    
    
    XJLog(@"====请求参数:%@",qingQiuCanShuDic);
    
    // 在.h 中查看服务器返回的JSON数据。
    [XJHttpTool requestBuyNowWithDic:qingQiuCanShuDic successH:^(id responseObjc) {

        
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObjc options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        XJLog(@"%@",jsonStr);
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        
        if ([code isEqualToString:@"0"]) {
            NSDictionary *contentDic =  responseObjc[@"data"][@"content"];
            // 一:总费用:单独记录
            self.total_fee = [NSString stringWithFormat:@"%@",contentDic[@"total_fee"]];
            //二:店铺商品模型数组
            self.dataArray = [XJSureOrderShopModel mj_objectArrayWithKeyValuesArray:contentDic[@"shop"]];
            
            //三:地址Dic 将dic 传到View层,在view层处理相关逻辑
          
            //第一次赋值 如果字典不为空。记录收货地址id
            if (![contentDic[@"address"] isKindOfClass:[NSNull class]]) {
               self.receiveAddresId = [NSString stringWithFormat:@"%@",responseObjc[@"data"][@"content"][@"address"][@"id"]];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                // 将地址dic传递给表头 在view层处理相关逻辑。
                self.headerView.addressDic = contentDic[@"address"];
                
                // bottomView赋值
                [self.bottomView configureSureOrderBottomViewWithTotalPrice:self.total_fee];
            });
            
            self.failView.hidden = YES;

        }else {
            
            self.failView.hidden = NO;
            [JRToast showWithText:responseObjc[@"message"]];
        }
        
    } failH:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
    }];
}

#pragma mark - private - 组装下一个接口的请求参数
/**组装订单号*/
- (NSString *)assembleOrderSNWithResponseObject:(NSDictionary *)dic {
    NSMutableString *foreign_infos = [NSMutableString string];
    
    NSArray *order_snsArr = dic[@"data"][@"content"][@"order_sns"];
    if (order_snsArr.count) {
        for (NSString *str in order_snsArr) {
            [foreign_infos appendFormat:@"%@,",str];
        }
    }
    
    return foreign_infos.copy;
}

#pragma mark - XJSureOrderFailViewDelegage
- (void)sureOrderFailViewRetryAction {
    [self requestData];
}

@end
